#include <connection.h>
#include <query.h>
#include <exceptions.h>

#include "sqlpool.h"

asud_connection_pool::asud_connection_pool(const std::string &_server, const std::string &_user, const std::string &_password, const std::string &_db):
    db_(_db),
    server_(_server),
    user_(_user),
    password_(_password)
{
}

asud_connection_pool::~asud_connection_pool()
{
    clear();
}

mysqlpp::Connection *asud_connection_pool::create()
{
  mysqlpp::Connection *con = new mysqlpp::Connection(false);
  
  if (con && con->connect( db_.c_str(), server_.c_str(), user_.c_str(), password_.c_str()))
  {
	mysqlpp::Query query(con);

	query << "set names 'utf8'";
	
	query.execute();

	query.enable_exceptions();
  }
  else
  {
	  delete con;
	  throw mysqlpp::ConnectionFailed();
  }
  
  return con;
}

void asud_connection_pool::destroy( mysqlpp::Connection *con )
{
    delete con;
}

unsigned int asud_connection_pool::max_idle_time()
{
    return 20;          //  TODO: read from config
}

